package cn.hejiang.mamis.core.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import cn.hejiang.mamis.core.entity.BaseEntity;
import cn.hejiang.mamis.core.service.ContextService;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;

public class QueryUtil {

	public static <T extends BaseEntity> QueryWrapper<T> newQueryWrapper(Class<T> entityClass) {
		ContextService contextService = SpringUtil.getBean(ContextService.class);
		return newQueryWrapper(contextService.getSystem().getId(), entityClass);
	}

	public static <T extends BaseEntity> QueryWrapper<T> newQueryWrapper(String sysId, Class<T> entityClass) {
		final QueryWrapper<T> query = new QueryWrapper<>();

		// 设置 entityClass
		query.setEntityClass(entityClass);

		// 处理组织条件
		query.eq("OWN_SYS_ID", sysId);

		// 处理删除条件
		query.eq("DELETED", 0);

		return query;
	}

	public static <T> QueryWrapper<T> withQueryCondition(final QueryWrapper<T> wrapper,
			final HttpServletRequest request) {
		final QueryWrapper<T> query = wrapper != null ? wrapper : new QueryWrapper<>();

		// 处理字段条件
		for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
			if (!ReflectUtil.hasField(query.getEntityClass(), entry.getKey())) {
				continue;
			}

			String column = StringUtil.toSqlColumn(entry.getKey());
			query.and(i -> {
				for (String value : entry.getValue()) {
					i.or().eq(column, value);
				}
			});
		}

		return query;
	}

	public static <T extends BaseEntity> UpdateWrapper<T> newDeleteWrapper(String id) {
		ContextService contextService = SpringUtil.getBean(ContextService.class);
		UpdateWrapper<T> updater = new UpdateWrapper<T>();

		updater.eq("ID", id);
		updater.eq("OWN_SYS_ID", contextService.getSystem().getId());
		updater.set("DELETED", 1);

		return updater;
	}

	public static <T extends BaseEntity> UpdateWrapper<T> newUpdateWrapper(final String id) {
		ContextService contextService = SpringUtil.getBean(ContextService.class);
		final UpdateWrapper<T> query = new UpdateWrapper<>();

		query.eq("ID", id);
		query.eq("OWN_SYS_ID", contextService.getSystem().getId());
		query.eq("DELETED", 0);

		return query;
	}
}
